<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="描述" prop="fileDescription">
        <el-input
          v-model="queryParams.fileDescription"
          placeholder="请输入描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上传人" prop="uploadName">
        <el-input
          v-model="queryParams.uploadName"
          placeholder="请输入上传人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件" prop="fileUrl">
        <el-input
          v-model="queryParams.fileUrl"
          placeholder="请输入文件"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['file:updown:add']"
        >上传新文件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['file:updown:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="updownList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="文件id" align="center" prop="fileId" />
        <el-table-column label="文件名称" align="center" prop="fileName" />
        <el-table-column label="描述" align="center" prop="fileDescription" />
        <el-table-column label="上传人" align="center" prop="uploadName" />
        <el-table-column label="文件类型" align="center" prop="fileType" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['decision:model:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['decision:model:remove']"
            >删除</el-button>
            <el-button type="text"
                       size="mini"
                       @click="downLoadFile(scope.row)"
                       class="table-inner-button"
            >下载</el-button>
          </template>
        </el-table-column>
      </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    <!-- 添加或修改模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称"/>
        </el-form-item>
        <el-form-item label="描述" prop="fileDescription">
          <el-input v-model="form.fileDescription" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="上传人" prop="uploadName">
          <el-input v-model="form.uploadName" placeholder="请输入上传人" />
        </el-form-item>
        <el-form-item label="文件类型" prop="uploadName">
          <el-input v-model="form.fileType" placeholder="请输入文件类型" :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="附件" prop="fileUrl">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :http-request="requestUpload"
            :on-change="uploadFiles"
            multiple :disabled="disabledupdate">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { listUpdown, getUpdown, delUpdown, addUpdown, updateUpdown , upload , downloadFile } from "@/api/file/updown";

export default {
  name: "file",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      updownList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileDescription: null,
        uploadName: null,
        fileType: null,
        fileUrl: null
      },
      disabled: true,
      disabledupdate: false,
      // 表单参数
      form:{
        fileUrl:'',
        fileName:'',
        fileType:'',
      },
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    downLoadFile(row){
      downloadFile(row.fileName).then(res=>{
        if (!res) {
          return
        }
        let url = window.URL.createObjectURL(new Blob([res]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', row.fileName)
        document.body.appendChild(link)
        link.click()
        // 释放URL对象所占资源
        window.URL.revokeObjectURL(url)
        // 用完即删
        document.body.removeChild(link)
      });
    },

    requestUpload() {
    },
    uploadFiles(file){
      let formData = new FormData();
      formData.append("file", file.raw);
      upload(formData).then(res => {
        let list = res.data[0].split("/")
        let type = res.data[0].split(".")
        this.form.fileType = type[type.length-1]
        this.form.fileUrl = res.data[0]
        this.form.fileName = list[list.length-1]
      });
    },

    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listUpdown(this.queryParams).then(response => {
        this.updownList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        fileName: null,
        fileDescription: null,
        createTime: null,
        uploadName: null,
        fileType: null,
        fileUrl: null
      };
      this.disabled=true,
      this.disabledupdate=false,
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disabledupdate=true
      const fileId = row.fileId || this.ids
      getUpdown(fileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateUpdown(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUpdown(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除文件编号为"' + fileIds + '"的数据项？').then(function() {
        return delUpdown(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('file/updown/export', {
        ...this.queryParams
      }, `updown_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
